package com.spark.actions.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.session.SqlSession;

import com.spark.core.Message;
import com.spark.core.SparkContext;
import com.spark.dao.SessionFactory;
import com.spark.util.IDGenerator;
import com.spark.util.InitializerHelper;
import com.spark.util.MemcachedHelper;


@SuppressWarnings("unchecked")
public class UserAction extends DefaultAction {
	
	
	public static final String FIELD_PASSWORD = "PASSWORD";
	public static final String FIELD_EMPLOYEE_ID = "EMPLOYEE_ID";
	public static final String FIELD_USER_ROLES_ADD = "USER_ROLES_ADD";
	public static final String FIELD_USER_ROLES_REMOVE = "USER_ROLES_REMOVE";

	private boolean validate(Map map, Message message, String action){
		if(ACTION_INSERT.equals(action)){
			return isNotEmpty(map.get(SparkContext.FIELD_USER_NAME), message,"登录名不能为空!") && 
			       isNotEmpty(map.get(FIELD_PASSWORD), message,"密码不能为空!") && 
			       isNotEmpty(map.get(FIELD_EMPLOYEE_ID), message,"员工不能为空!");
		}else{
			return isNotEmpty(map.get(SparkContext.FIELD_USER_NAME), message,"登录名不能为空!") && 
			       isNotEmpty(map.get(FIELD_EMPLOYEE_ID), message,"员工不能为空!");
		}
	}
	
	private boolean validateLogin(Map map, Message message) {
		return isNotEmpty(map.get(SparkContext.FIELD_COMPANY_CODE), message,"公司账号不能为空!") && 
		       isNotEmpty(map.get(FIELD_PASSWORD), message,"密码不能为空!") && 
		       isNotEmpty(map.get(SparkContext.FIELD_USER_NAME), message,"用户账号不能为空!");
	}
	
	
	/**
	 * 登陆系统
	 * @param context
	 * @throws Exception
	 */
	public void login(SparkContext context) throws Exception{
		Map data = getFormData(context);
		Message message = new Message(true);
		String wid = (String)data.get(SparkContext.SPARK_WINDOW_ID);
		if(wid == null || "".equals(wid)){
			message.setWarning("WID不正确!");
			message.setWidth(300);
			message.setHeiht(150);
		}else{
			if(validateLogin(data,message)){
				SqlSession sqlSession = SessionFactory.getSession();
				//TODO:密码不作为参数，表的unique 是company_id,user_name
				String passMD5 = DigestUtils.md5Hex((String)data.get(FIELD_PASSWORD));
	//			data.put(FIELD_PASSWORD,);
				Map map = (Map) sqlSession.selectOne("sys_user.selectLoginUser",data);
				if(map!=null && passMD5 != null && passMD5.equals(map.get(FIELD_PASSWORD))){
					String suk = IDGenerator.getInstance().generate();
					message.put(SparkContext.SPARK_USER_KEY,suk);
					message.put(SparkContext.SPARK_WINDOW_ID,wid);
					
					Integer userId = (Integer)map.get(SparkContext.FIELD_USER_ID);
					Integer companyId = (Integer)map.get(SparkContext.FIELD_COMPANY_ID);
					
					String companyKey = "C"+companyId;
					String userKey = userId + "_" + suk;
					List userList = (List)MemcachedHelper.get(companyKey);
					if(userList == null){
						userList = new ArrayList();
						userList.add(userKey);
					}else{
						boolean found = false;
						Iterator it = userList.iterator();
						while(it.hasNext()){
							String ukey = (String)it.next();
							String[] as = ukey.split("_");
							String userIdStr = as[0];
							if(userIdStr.equals(userId.toString())){
								found = true;
								break;
							}
						}
						if(!found) {
							userList.add(userKey);
						}else{
	//						SparkCometFacade.addDisconnectItem(companyId+"_"+userId+"_" + suk);
						}
					}
					//TODO:从帐套中取科目表ID
					InitializerHelper.initAccount(1);
					//TODO:把初始化的内容都放到Initialize中
					MemcachedHelper.set(companyKey,0,userList);
					StringBuilder sb = new StringBuilder();
					sb.append(userId).append("#");
					sb.append(companyId).append("#");
					sb.append(map.get(SparkContext.FIELD_COMPANY_NAME)).append("#");
					sb.append(map.get(SparkContext.FIELD_EMPLOYEE_NAME));
					MemcachedHelper.set(suk, 180, sb.toString());
				}else{
					message.setWarning("公司名用户名或者密码不正确!");
					message.setWidth(350);
					message.setHeiht(150);
				}
			}
		}
		writeMessage(context, message);
	}
	
	/**
	 * 创建系统账号.
	 * @param context
	 * @throws Exception
	 */
	public void createUser(SparkContext context) throws Exception {
		doExecute(context, "sys_user.insert", ACTION_INSERT);
	}
	
	/**
	 * 更新系统账号.
	 * @param context
	 * @throws Exception
	 */
	public void updateUser(SparkContext context) throws Exception {
		doExecute(context, "sys_user.update", ACTION_UPDATE);
	}
	
	/**
	 * 删除系统账号.
	 * @param context
	 * @throws Exception
	 */
	public void deleteUser(SparkContext context) throws Exception {
		Map requestData = getRequestData(context);
		List list = (List)requestData.get(PARAMETER);
		Message message = new Message(true);
		if(list!=null){
			SqlSession sqlSession = SessionFactory.getSession(false);
			try {
				Iterator it = list.iterator();
				while(it.hasNext()){
					Map user = (Map)it.next();
					setCompanyId(user, context);
					doAction(sqlSession, ACTION_DELETE, "sys_user.delete", user);	
					doAction(sqlSession, ACTION_DELETE, "sys_user_role.deleteByUser", user);					
				}
				
				sqlSession.commit();
			} finally {
				SessionFactory.closeSession(sqlSession);
			}
		}
		message.setResult(list);
		writeMessage(context, message);
		
	}
	
	protected void doExecute(SparkContext context, String statement, String action) throws Exception{
		Map requestData = getRequestData(context);
		List list = (List)requestData.get(PARAMETER);
		Message message = new Message(true);
		if(list!=null && list.size() > 0){
			Map map = (Map)list.get(0);
			if(validate(map,message, action)){
				SqlSession sqlSession = SessionFactory.getSession(false);
				try {
					setCompanyId(map, context);
					if(ACTION_INSERT.equals(action)){
						String pass = (String)map.get(FIELD_PASSWORD);
						map.put(FIELD_PASSWORD,DigestUtils.md5Hex(pass));
					}
					Integer count = (Integer)sqlSession.selectOne("sys_user.selectDuplicateUser", map);
					if(count>0){
						message.setWarning("已经存在登陆名为\""+map.get(SparkContext.FIELD_USER_NAME)+"\"的账户!");
						message.setWidth(300);
						message.setHeiht(150);
					}else{
						doAction(sqlSession, action, statement, map);
						Integer userId = (Integer)map.get(SparkContext.FIELD_USER_ID);
						//角色列表删除
						List removeList = (List)map.get(FIELD_USER_ROLES_REMOVE);
						if(removeList!=null){
							Iterator it = removeList.iterator();
							while(it.hasNext()){
								Map role = (Map)it.next();
								doAction(sqlSession, ACTION_DELETE, "sys_user_role.delete", role);	
							}
						}
						
						//角色列表新增
						List userList = (List)map.get(FIELD_USER_ROLES_ADD);
						if(userList!=null){
							List addList = new ArrayList();
							Iterator it = userList.iterator();
							while(it.hasNext()){
								Map role = (Map)it.next();
								role.put(SparkContext.FIELD_USER_ID, userId);
								setCompanyId(role, context);
//								setDefault(role,FIELD_COMPANY_ID,getCompanyId(context));
								addList.add(role);
							}
							if(addList.size() >0){
								Map roleMap = new HashMap();
								roleMap.put("items", addList);
								sqlSession.insert("sys_user_role.batchInsert",roleMap);
							}
						}
					}
					sqlSession.commit();
				} finally {
					SessionFactory.closeSession(sqlSession);
				}
			}
		}
		writeMessage(context, message);
	}
	
	
	
}
